package com.example.java.base.rabbitmq.a2workqueue;

import com.example.java.base.rabbitmq.util.RabbitMqUtil;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;

/**
 * Consumer:消费消息
 *
 * @author zhangxiaoxiang
 * @date 2020/11/15
 */
public class Consumer1 {
    public static void main(String[] args) {
        try {
            // 获取connection
            Connection connection = RabbitMqUtil.getConnection();
            // 获取channel
            final Channel channel = connection.createChannel();
            //每次消费1个
            channel.basicQos(1);
            channel.queueDeclare("work", true, false, false, null);
            //默认是负载均衡型 参数1:队内名称 参数2:消息是否自动确认
            channel.basicConsume("work", false, new DefaultConsumer(channel) {
                @lombok.SneakyThrows
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException {
                    //模拟延迟消费,区别消费能力
                    Thread.sleep(1000);
                    System.out.println("消费者-1: " + new String(body));
                    //注意这里不加手动确认
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            });
            //    消费端应该处于监听状态,一般不用关闭连接
            // 	channel.close();
            // 	connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}